/* SHOW All Registered Users */
$(function() {
	var pager;
	var show;

	var urlJson = "goRegisteredUsersJson.json";
	showTable(urlJson);
	// End - Slide row
});

function showTable(string) {
	$("#tablepaging > tbody").html("");
	$
			.getJSON(
					string,
					{
						ajax : 'true'
					},
					function(data) {
						var length = data.length;
						var color = "";
						var username = "";
						var row = 0;

						if (length == 0) {
							var content = '<tr>';
							content += '<td colspan="8" style="text-align:center;">';
							content += 'No matching User Account found';
							content += '</td>';
							content += '</tr>';
							$("#tablepaging > tbody").append(content);
						} else {
							for (var i = 0; i < length; i++) {
								row++;
								if (data[i].accountMidName == null) {
									data[i].accountMidName = "";
								}
								var content = "<tr>";
								content += "<td>";
								content += "<input type='hidden' id='accountLoginId"
										+ (i + 1)
										+ "' value='"
										+ data[i].accountLoginId + "'>";
								content += "<input type='checkbox' class='inbox-checkbox' name='listCheckbox' value='"
										+ data[i].accountLoginId
										+ "'>"
										+ "</td>";
								content += "<td style=\"text-align:center;\">"
										+ (i + 1) + "</td>";
								content += "<td style=\"text-align:center;\">"
										+ data[i].role + "</td>";
								content += "<td style=\"text-align:center;\">"
										+ data[i].accountLoginId
										+ "</td style=\"text-align:center;\">";
								content += "<td style=\"text-align:center;\">"
										+ data[i].accountFirstName + " "
										+ data[i].accountMidName + " "
										+ data[i].accountLastName
								"</td>";
								content += "<td style=\"text-align:center;\">"
										+ data[i].accountEmail1 + " </td>";
								if (data[i].status == "Active") {
									color = "green";
								}
								if (data[i].status == "Disable") {
									color = "red";
								}
								content += "<td class='cell-status hidden-phone hidden-tablet' style=\"text-align:center;\"> <b style='background-color:"
										+ color
										+ "'>"
										+ data[i].status
										+ "</b> </td>";
								username = data[i].userName;
								content += "<td class='cell-time' style='text-align: center'><button type=\"button\" id=\"btnShowProfile"
										+ (i + 1)
										+ "\" class=\"btn btn-group btn-primary\" name=\"action\" value=\"Edit\">Edit</button></td>";
								content += "</tr>";
								$("#tablepaging > tbody").append(content);
							}
						}

						document.getElementById("numberOfRow").value = row;

						// Init paging
						// Set number of row per pages
						pager = new Pager('tablepaging', 20);
						pager.init();
						pager.showPageNav('pager', 'pageNavPosition');
						pager.showPage(1);
						// End - Init paging

						show = new ActionShow();
					});
}

// Show detailed Registered User
function ShowDetail(event, row) {
	$("#messagePanel").hide();
	var accountLoginID = $("#accountLoginId" + row).val();
	var show;
	var validate;
	// Start Load Detail
	jQuery
			.ajax({
				url : 'registeduserdetailjson/' + accountLoginID + '.json',
				method : 'POST',
				contentType : 'application/json',
				data : $('#btnShowProfile' + row).serialize()
			})
			.done(
					function(data) {
						// Do something with the response
						var length = data.length;
						$("#detailContent").html("");

						var content = "";

						if (data.accountMidName == null) {
							data.accountMidName = "";
						}
						if (data.accountPhone2 == null) {
							data.accountPhone2 = "";
						}
						if (data.accountAddress2 == null) {
							data.accountAddress2 = "";
						}
						if (data.accountEmail2 == null) {
							data.accountEmail2 = "";
						}
						content += '<div class="module-head" style="text-align: center;">';
						content += '<h3>' + data.accountFirstName + ' '
								+ data.accountMidName + ' '
								+ data.accountLastName + ' Profile</h3>';
						content += '</div>';

						content += '<div style="margin-top: 20px;margin-left: 20%;">';
						// Account Login ID
						content += '<div style="width: 250px; margin-left: 30px; float: left">';
						content += '<div class="controls row-fluid">';
						content += '<input style="width: 150px;" name="txtRequestUsername" id="txtNUsername" type="hidden" readonly="true" placeholder="Username" value="'
								+ data.accountLoginId + '" />';
						content += '</div></div>';
						// End - Account Login ID

						// ID Card Number
						content += '<div style="margin-left: 30px; float: left">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNIDCard" style="display:inline;float:left;">ID Card Number: </label>'
								+ '<input name="txtIdCardNumber" type="text" id="txtNIDCard" value="'
								+ data.accountIDCardNumber
								+ '" placeholder="ID Card Number" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - ID Card Number

						// First Name
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNFirstName" style="display:inline;float:left;">First Name: </label>'
								+ '<input name="txtFirstName" type="text" id="txtNFirstName" value="'
								+ data.accountFirstName
								+ '" placeholder="First Name" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - First Name

						// Middle Name
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNMidName" style="display:inline;float:left;">Middle Name: </label>'
								+ '<input name="txtMidName" type="text" id="txtNMidName" value="'
								+ data.accountMidName
								+ '" placeholder="Middle Name" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Middle Name

						// Last Name
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNLastName" style="display:inline;float:left;">Last Name: </label>'
								+ '<input name="txtLastName" type="text" id="txtNLastName" value="'
								+ data.accountLastName
								+ '" placeholder="Last Name" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Last Name

						// Phone
						// Phone 1
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNPhone1" style="display:inline;float:left;">Phone 1: </label>'
								+ '<input name="txtPhone1" type="text" id="txtNPhone1" value="'
								+ data.accountPhone1
								+ '" placeholder="Phone 1" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Phone 1
						// Phone 2
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNPhone2" style="display:inline;float:left;">Phone 2: </label>'
								+ '<input name="txtPhone2" type="text" id="txtNPhone2" value="'
								+ data.accountPhone2
								+ '" placeholder="Phone 2" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Phone 2
						// End - Phone

						// Email
						// Email 1
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNEmail1" style="display:inline;float:left;">Email 1: </label>'
								+ '<input name="txtEmail1" type="text" id="txtNEmail1" value="'
								+ data.accountEmail1
								+ '" placeholder="Email 1" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Email 1
						// Email 2
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNEmail2" style="display:inline;float:left;">Email 2: </label>'
								+ '<input name="txtEmail2" type="text" id="txtNEmail2" value="'
								+ data.accountEmail2
								+ '" placeholder="Email 2" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Phone

						// Address
						// Address 1
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNAddress1" style="display:inline;float:left;">Address 1: </label>'
								+ '<input name="txtAddress1" type="text" id="txtNAddress1" value="'
								+ data.accountAddress1
								+ '" placeholder="Address 1" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Address 1
						// Address 2
						content += '<div style="margin-left: 30px; float: left;clear: both;">';
						content += '<div style="width:400px;display:block">';
						content += '<label for="txtNAddress2" style="display:inline;float:left;">Address 2: </label>'
								+ '<input name="txtAddress2" type="text" id="txtNAddress2" value="'
								+ data.accountAddress2
								+ '" placeholder="Address 2" style="width: 250px;margin-left:15px;text-align:center;float:right;"/>';
						content += '</div></div>';
						// End - Address 2
						// End - Address
						content += '</div>';

						// Button Controll
						content += '<div style="margin-top: 30px; clear: both">';
						content += '<div class="controls clearfix">';
						content += '<button type="button" class="btn btn-primary pull-left" style="margin-left: 15px;" id="btnSaveNewProfile">Save</button>';
						content += '<button type="reset" class="btn btn-primary pull-left" style="margin-left: 15px;">Refresh</button>';
						content += '<button id="btnHideDetailApprove" type="button" class="btn btn-primary pull-left" style="margin-left: 15px;">Close</button>';
						content += '</div>';
						content += '</div>';
						// End - Button Controll

						$("#detailContent").append(content);
						show = new ActionShow();
						validate = new actionValidate();
					}).fail(function() {
				// Whoops; show an error.
				alert("failed to load registered users");
			});

	// End - Start Load Detail
};
// End - Show detailed Registered User

function ActionShow() {
	function generate_ShowProfileFandler(row) {
		return function(event) {
			ShowDetail
			show = new ShowDetail(event, row);
			$("#messagePanel").hide();
			$("#panelAdvanceSearch").slideUp("slow");
			$("#panelProfileDetail").slideDown("slow");
		};
	}

	// Slide row
	function generate_HideProfileFandler() {
		return function(event) {
			$("#panelProfileDetail").slideUp("slow");
		};
	}

	// Detail Profile
	numberOfRow = $("#numberOfRow").val();

	// Generate
	for (var i = 1; i <= numberOfRow; i++) {
		var row = i.toString();

		$('#btnShowProfile' + row).click(generate_ShowProfileFandler(row));

		$('#btnHideDetailApprove').click(generate_HideProfileFandler());
	}

	// End - Detail Profile
}

function actionValidate() {
	// Validate Profile Form BackEnd
	$("#btnSaveNewProfile").click(
			function() {
				var form = $("#DetailRegisteredUserForm");
				form.validate();
				
				//Check whether front-end validation is success or not.
				if (form.valid() == false) {
					$("#messagePanel").hide();
					event.preventDefault();
				} else {
					// Get value from profile form
					var username = $('#txtNUsername').val();
					var idCard = $('#txtNIDCard').val();
					var fisrtName = $('#txtNFirstName').val();
					var midName = $('#txtNMidName').val();
					var lastName = $('#txtNLastName').val();
					var phone1 = $('#txtNPhone1').val();
					var phone2 = $('#txtNPhone2').val();
					var address1 = $('#txtNAddress1').val();
					var address2 = $('#txtNAddress1').val();
					var email1 = $('#txtNEmail1').val();
					var email2 = $('#txtNEmail2').val();
					// End - Get value from profile form

					if (username == "") {
						username = "null";
					}

					if (idCard == "") {
						idCard = "null";
					}

					if (fisrtName == "") {
						fisrtName = "null";
					}

					if (midName == "") {
						midName = "null";
					}

					if (lastName == "") {
						lastName = "null";
					}

					if (phone1 == "") {
						phone1 = "null";
					}

					if (phone2 == "") {
						phone2 = "null";
					}

					if (address1 == "") {
						address1 = "null";
					}

					if (address2 == "") {
						address2 = "null";
					}

					if (email1 == "") {
						email1 = "null";
					}

					if (email2 == "") {
						email2 = "null";
					}

					var urlJson = 'validateNewProfile/' + username + '/'
							+ idCard + '/' + fisrtName + '/' + midName + '/'
							+ lastName + '/' + phone1 + '/' + phone2 + '/'
							+ address1 + '/' + address2 + '/' + email1 + '/'
							+ email2 + '.json';

					jQuery.ajax({
						url : urlJson,
						method : 'POST',
						contentType : 'application/json',
						data : $('#btnSaveNewProfile').serialize()
					}).done(function(data) {
						// Do something with the response

						$("#messagePanel").html("");

						var content = data[0];

						if (content == "valid") {
							// submit if all properties are validated
							// successfully
							$("#messagePanel").hide();
							$("#DetailRegisteredUserForm").submit();
						} else {
							// show error message
							$("#messagePanel").show();
							$("#messagePanel").append(content);
						}
					}).fail(function() {
						// Whoops; show an error.
						alert("failed to load validate message");
					});
				}
			});
	// End - Validate Profile Form BackEnd
}

$(document)
		.ready(
				function() {
					// Advance Search
					$("#btnShowAdvanceSearch").click(function() {
						$("#panelProfileDetail").slideUp("slow");
						$("#panelAdvanceSearch").slideDown("slow");
					});

					$("#btnHideAdvanceSearch").click(function() {
						$("#panelAdvanceSearch").slideUp("slow");
					});

					// End - Advance Search

					// Checkbox all
					$(document).ready(function() {
						$('#checkAll').click(function(event) { // on click
							if (this.checked) { // check select status
								$('.inbox-checkbox').each(function() { // loop
									// through
									// each
									// checkbox
									this.checked = true; // select all
									// checkboxes
									// with
									// class "checkbox1"
								});
							} else {
								$('.inbox-checkbox').each(function() { // loop
									// through
									// each
									// checkbox
									this.checked = false; // deselect all
									// checkboxes
									// with
									// class "checkbox1"
								});
							}
						});

					});
					// End - Checkbox all

					// Search Advanced
					$("#btnAdvancedSearch").click(
							function() {
								var pager;
								var show;

								// Get value from advanced search panel
								var fullName = $('#txtSFullName').val();
								var username = $('#txtSUsername').val();
								var idCard = $('#txtSIDCard').val();
								var phone = $('#txtSPhone').val();
								var address = $('#txtSAddress').val();
								var email = $('#txtSEmail').val();
								var role = $('#txtSRole').val();
								var status = $('#txtSStatus').val();
								// End - Get value from advanced search panel

								/*
								 * var variable = [ fullName, username, idCard,
								 * phone, address, date, email, role, status ];
								 * 
								 * for (var int = 0; int < variable.length;
								 * int++) { var variable_element =
								 * variable[int]; if (variable_element == "") {
								 * variable[int] = "null"; } }
								 */

								if (username == "") {
									username = "null";
								}

								if (fullName == "") {
									fullName = "null";
								}

								if (idCard == "") {
									idCard = "null";
								}

								if (phone == "") {
									phone = "null";
								}

								if (address == "") {
									address = "null";
								}

								if (email == "") {
									email = "null";
								}

								if (role == "") {
									role = "null";
								}

								if (status == "") {
									status = "null";
								}

								if (username == "") {
									username = "null";
								}

								var urlJson = "advancedSearchRegisteredUsers/"
										+ fullName + "/" + username + "/"
										+ idCard + "/" + phone + "/" + address
										+ "/" + email + "/" + role + "/"
										+ status + ".json";

								$.ajax({
									type : "GET",
									url : urlJson,
									success : function(response) {
										showTable(urlJson);
									},
								});

							});
					// End - Search Advanced DetailRegisteredUserForm
					// Validate Profile Form Front - End
					$("#DetailRegisteredUserForm").submit(function(event) {
						// event.preventDefault();
					});

					$('#DetailRegisteredUserForm')
							.validate(
									{
										rules : {
											txtIdCardNumber : {
												required : true,
												number : true,
												rangelength : [ 9, 12 ]
											},
											txtFirstName : {
												required : true,
												rangelength : [ 0, 20 ]
											},
											txtLastName : {
												required : true,
												rangelength : [ 0, 20 ]
											},
											txtMidName : {
												rangelength : [ 0, 20 ]
											},
											txtAddress1 : {
												required : true,
											},
											txtEmail1 : {
												required : true,
												email : true,
											},
											txtEmail2 : {
												email : true,
											},
											txtPhone1 : {
												required : true,
												number : true,
												rangelength : [ 9, 12 ]
											},
											txtPhone2 : {
												number : true,
												rangelength : [ 9, 12 ]
											}
										},
										messages : {
											txtIdCardNumber : {
												required : "What's your ID Card Number?",
												number : "Please enter valid number!",
												rangelength : "Invalid ID, use [9 - 12] digit number"
											},
											txtFirstName : {
												required : "What's your first name?",
												rangelength : "Too long, Please use your real name"
											},
											txtLastName : {
												required : "What's your last name?",
												rangelength : "Too long, Please use your real name"
											},
											txtMidName : {
												rangelength : "Too long, Please use your real name"
											},
											txtAddress1 : {
												required : "What's your Address?"
											},
											txtEmail1 : {
												required : "What's your Email?",
												email : "Invalid email! Ex: James@csc.com"
											},
											txtEmail2 : {
												email : "Invalid email! Ex: James@csc.com"
											},
											txtPhone1 : {
												required : "What's your Phone Number?",
												number : "Invalid Phone number",
												rangelength : "Invalid Phone, use [9 - 12] digit number"
											},
											txtPhone2 : {
												number : "Invalid Phone number",
												rangelength : "Invalid Phone, use [9 - 12] digit number"
											}
										},
										highlight : function(element) {
											$(element).closest('.field')
													.removeClass('success')
													.addClass('error');
										},
										success : function(element) {
											element.text('').addClass('valid')
													.closest('.field')
													.removeClass('error')
													.addClass('success');
										}
									});
					// End - Validate Profile Form Front - End
				});
/* End - JSON */